﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Xml;
using SharpObjects.Configuration;
using SharpObjects.Configuration.ConfigurationProviders;
using SharpObjects.Interfaces;
using SharpRuleEngineTest.RuleElements;
using SharpObjects.RuleEngine;

namespace SharpRuleEngineTest.Rules
{
    public class AppendToFileRule : IInitializable, IRule
    {
        public FieldElement TextField { get; set; }
        public string FileNameField { get; set; }
        public eDataStore DataStore { get; set; }
        
        #region IInitializable Members

        public void Initialize(XmlElement initializationElement)
        {
            XmlConfigurationProvider init = new XmlConfigurationProvider(initializationElement);

            TextField = init.GetObject<FieldElement>("field");
            FileNameField = init.GetString("@file_name_field");
            DataStore = init.GetEnum<eDataStore>("@data_store");
        }

        #endregion

        #region IRule Members

        public void Execute(ref IRuleEngineContext ruleEngineContext, IDataProvider dataProvider)
        {
            string text = (string)TextField.GetValue(ruleEngineContext, dataProvider);
            string fileName;

            if(DataStore == eDataStore.Data)
            {
                fileName = dataProvider.GetString(FileNameField);
            }
            else
            {
                fileName = ruleEngineContext.GetValue<string>(FileNameField);
            }

            File.AppendAllText(fileName, text);
        }

        #endregion
    }
}
